<template>
	<div class="">
		<div class="flex flex-wrap -mb-2">
			<sports-single-nav-dropdown :region-list="regionList" @select="onSelect" />
			<up-toggle-popular
				:checked="!leagueId"
				class="mx-2 mb-2"
				@click="onSelect('')"></up-toggle-popular>
			<sports-single-nav-item
				v-for="item in showLeagueList"
				:key="item.leagueId"
				:data="item"
				:active="leagueId === item.leagueId"
				@click="onSelect(item.leagueId)" />
		</div>
	</div>
</template>

<script lang="ts" setup>
import { UpTogglePopular } from '@/components/up'
import SportsSingleNavDropdown from './sports-single-nav-dropdown.vue'
import SportsSingleNavItem from './sports-single-nav-item.vue'
import { getLeagues, getSportsRegions } from '@/api/betting'
import { watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/store'
import { useRequest } from '@/hooks'
import { LeagueType, RegionType } from '@/types'

const props = defineProps({
	sportId: {
		type: String
	}
})

const route = useRoute()
const router = useRouter()

const appStore = useAppStore()

const leagueId = computed(() => route.params.leagueId || '')

const onSelect = (val: string) => {
	let path = '/sports/' + route.params.id
	if (val) {
		path += '/' + val
	}
	router.push(path)
}

const showLeagueList = computed(() => {
	if (leagueId.value) {
		const region = regionList.value.find(({ leagues }) =>
			leagues.some((league) => league.leagueId === leagueId.value)
		)
		if (region) {
			return region.leagues
		}
	}
	return leagueList.value
})

const { run: runLeagues, list: leagueList } = useRequest<LeagueType>(getLeagues, {
	pageSize: 30
})

const { run: runRegions, list: regionList } = useRequest<RegionType>(getSportsRegions)

watch(
	() => route.params.id,
	(val) => {
		if (val) {
			runLeagues(
				{
					sportIDs: props.sportId,
					locale: appStore.lang,
					location: appStore.region,
					hasValidEvents: true,
					isRecommend: true
				},
				{ refresh: true }
			)
			runRegions(
				{
					sportId: props.sportId,
					locale: appStore.lang,
					location: appStore.region
				},
				{ refresh: true }
			)
		}
	},
	{
		immediate: true
	}
)
</script>
